#include "../source/server.hpp"

EventLoop base_loop;
LoopThreadPool *loop_pool;
std::unordered_map<uint64_t, PtrConnection> _conns;
void OnConnected(const PtrConnection &conn)
{
    DBG_LOG("new connection : %ld", conn->Id());
}

void ConnectDestroy(const PtrConnection &conn)
{
    DBG_LOG("destroy connection: %ld", conn->Id());
    _conns.erase(conn->Id());
}

void OnMessage(const PtrConnection &conn, Buffer *buf)
{
    DBG_LOG("%s", buf->ReadPosition());
    buf->MoveReadOffset(buf->ReadableSize());
    std::string str = "nightcord";
    conn->Send(str.c_str(), str.size());
}

void NewConnection(int fd)
{

    uint64_t conn_id = rand() % 10000;

    PtrConnection conn(new Connection(loop_pool->NextLoop(), conn_id, fd));

    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    conn->SetSrvClosedCallback(std::bind(ConnectDestroy, std::placeholders::_1));
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));

    conn->EnableInactiveRelease(10);

    conn->Established(); // 就绪初始化

    _conns.insert({conn_id, conn});
    DBG_LOG("new ----------------------------");
}

int main()
{
    srand(time(nullptr));
    loop_pool = new LoopThreadPool(&base_loop);
    loop_pool->SetThreadCount(2);
    loop_pool->Create();
    Acceptor acceptor(&base_loop, 21000);

    acceptor.SetAcceptCallback(std::bind(NewConnection, std::placeholders::_1));

    acceptor.Listen();

    base_loop.Start();

    return 0;
}